// Package cmd @author <chengjiang@buffalo-robot.com>
// @date 2023/1/13
// @note
package cmd

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/spf13/cobra"
)

// flags
var (
	endpot            string
	acckeyid          string
	secret            string
	bucket            string
	objname           string
	localfilefullname string
)

// rootCmd represents the base command when called without any subcommands
var ossCmd = &cobra.Command{
	Use:   "oss [flags]",
	Short: "oss comand, used to upload the file to oss",
	Long: `oss, 
used to upload the file to web.
	postfile：
		1. oss: 将结果文件同步到阿里OSS中。`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	Run: func(cmd *cobra.Command, args []string) {
		// oss
		//ossInit()
		// 上传文件
		uploadFile()
	},
}

func init() {
	// oss:
	Conf.oss.accessKeyID = "LTAI4GJAtq5WBvytduM5FJr8"
	Conf.oss.accessKeySecret = "6hzU5i4k9NkdFV4fAGQbWfXU1L3Kbw"
	Conf.oss.ossEndpoint = "oss-cn-chengdu.aliyuncs.com"
	Conf.oss.bucketName = "bris4-app-publisher"
	//init
	ossInit()
	// Here you will define your flags.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.
	//
	ossCmd.Flags().StringVarP(&objname, "objname", "o", "", "on the oss system, the file path with name")
	ossCmd.Flags().StringVarP(&localfilefullname, "localfilefullname", "l", "", "the local absolute file path with the name.")
}

func ossInit() {
	endpot = Conf.oss.ossEndpoint
	acckeyid = Conf.oss.accessKeyID
	secret = Conf.oss.accessKeySecret
	bucket = Conf.oss.bucketName
}

func uploadFile() error {
	//
	println("开始oss上传操作......loading...")
	// 创建oss 实例：
	client, err := oss.New(endpot, acckeyid, secret)
	if err != nil {
		handleError(err)
	}

	// 获取存储空间
	fmt.Println("bucket Name: ", bucket)
	buk, err1 := client.Bucket(bucket)
	if err1 != nil {
		handleError(err1)
	}
	// upload
	err = buk.PutObjectFromFile(objname, localfilefullname)
	if err != nil {
		handleError(err)
	}
	return err
}
